<template>
  <div class="mapContain">
    <div class="tabContent">
      <div class="tab">2D</div>
      <el-button type="primary" size="small" @click="go">返回</el-button>
    </div>
    <div class="top">
      <div class="up">底图上传</div>
      <el-upload
        :class="{uoloadSty:showUpload,disUoloadSty:noshowUpload}"
        :action="upload"
        list-type="picture-card"
        :on-change="changeImage"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess"
        :file-list="imgList"
        :limit="1"
      >
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <div ref="map" class="map"></div>
    <div class="button-wrapper w-full flex justify-center mb-2">
      <vs-button
        color="primary"
        type="filled"
        icon-pack="feather"
        icon="icon-check"
        size="small"
        class="bg-primary-gradient"
        @click="save"
      >保存</vs-button>
    </div>
    <vx-popup
      title="配置测点"
      width="680px"
      @close="cancelFormSubmit"
      :active.sync="add"
      @confirmPopup="submit"
      @cancelPopup="cancelFormSubmit"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="测点配置" prop="name">
          <el-select v-model="ruleForm.name" placeholder="请选择测点">
            <el-option
              v-for="(item, index) in list"
              :key="index"
              :label="item.name"
              :value="`${item.name}@${item.id}*${item.code}`"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </vx-popup>
  </div>
</template>

<script>
import mapboxgl from "mapbox-gl";
import base from "../../../api/base";
export default {
  name: "add",
  props: {
    crossSectionId: {
      type: String
    },
    ownId: {
      type: String
    },
    isShow: {
      type: Boolean
    },
    sectionId: {
        type: String
    },
    value: {
        type: Object,
        default(){
            return {}
        }
    }
  },
  data() {
    return {
         upload: base.UPLOADURL,
      download: base.DOWNLOADURL,
      show: false,
      showUpload: true,
      noshowUpload: false,
      add: false,
      ruleForm: {
        name: ""
      },
      rules: {},
      list: [],
      imageUrl: require("../../../assets/mapbox/bg.png"),
      imgList: [],
      path: "",
      e: {},
      arr: [],
      pointList: [],
      repeatList:[],
      first: false,
      geojson: {
        type: "FeatureCollection",
        features: []
      },
      zoom: 16.9, // 缩放级别
      proportion: "", //图片比例
      yPoint: 0.0010127542875721929,
      coordinates: [
        [-76.54335737228394, 39.18579907229748],
        [-76.52803659439087, 39.1838364847587],
        [-76.5295386314392, 39.17683392507606],
        [-76.54520273208618, 39.17876344106642]
      ]
    };
  },
  mounted() {
    this.getMap();
  },
  watch: {
    'crossSectionId': {
      handler(val, old) {
        this.getList();
      },
      immediate: true
    }
  },
  methods: {
    go() {
      this.show = true;
      this.$emit("go", this.show);
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.path = res.data.successFiles[0].filePath;
      var img = new Image();
      img.src = this.download + this.path;
      img.onload = () => {
        this.proportion = (Number(img.width) / Number(img.height)).toFixed(2);
        let xPoint = this.proportion * this.yPoint;
        this.coordinates = [
          [-xPoint, this.yPoint],
          [xPoint, this.yPoint],
          [xPoint, -this.yPoint],
          [-xPoint, -this.yPoint]
        ];
      };
      setTimeout(() => {
        var map = this.map.getSource("overlay");
        map.updateImage({ url: this.imageUrl });
        map.setCoordinates(this.coordinates);
      }, 1000);
    },
    changeImage(file, fileList) {
      this.noshowUpload = fileList.length >= 1;
    },
    handleRemove(file, fileList) {
      this.imageUrl = "";
      this.path = "";
      this.pointList = [];
      this.first = true;
      var map = this.map.getSource("overlay");
      map.updateImage({ url: require("../../../assets/mapbox/bg.png") });
      this.arr.map(v => {
        v.remove();
      });
      this.list.map(v => {
        v.disabled = false;
      });
      this.noshowUpload = false;
    },
    submit() {
      let test = this.ruleForm.name.substring(
        0,
        this.ruleForm.name.indexOf("@")
      );
      // console.log("测试++++++++++++++++++++++++++name+++++++",this.ruleForm.name)
      let id = this.ruleForm.name.substring(
        this.ruleForm.name.indexOf("@") + 1,this.ruleForm.name.indexOf("*")
      );
      // console.log("测试+++++++++++++++++++++++++++++++++++",id)
      let code = this.ruleForm.name.substring(this.ruleForm.name.indexOf("*") + 1)
      if (test != null && test != "") {
        this.list.map(v => {
          if (v.name === test) {
            v.disabled = true;
          }
        });
        let data = {
          type: "Feature",
          properties: {
            message: test,
            id: id,
            code: code,
            iconSize: [80, 80]
          },
          geometry: {
            type: "Point",
            coordinates: [this.e.lngLat.lng, this.e.lngLat.lat]
          }
        };
        // console.log("测试+++++++++++++++++++++++++++++++++++",data)
        //调用创建dom 生成marker 方法
        this.initMarker(data);
        this.pointList.push(data);
      }
      this.add = false;
      this.ruleForm.name = "";
    },
    cancelFormSubmit() {
      this.add = false;
      this.ruleForm.name = "";
    },
    //初始化列表数据
    getList() {
      const params = {
        ownId: this.ownId,
        crossSectionId: this.crossSectionId
      };
      if (!this.crossSectionId) {
        return false;
      }
      this.$api.bridge
        .queryAllDeviceMeasurePointByBridgeIdAndCrossSectionId(params)
        .then(res => {
          if (res && res.data && res.data.data && res.data.data.length > 0) {
            res.data.data.map(v => {
              v.disabled = false;
            });
          }

          this.list = res && res.data.data ? res.data.data[0] : [];
          setTimeout(() => {
            this.get();
          }, 1000);
        });
    },
    // 初始化地图
    initMap() {
      mapboxgl.accessToken =
        // 原先的注释掉
        // "pk.eyJ1IjoieHVzaGFucGVpIiwiYSI6ImNqenl5M2t0aTA0dzczY3AzdXJoajB6emcifQ.Gpduip9bhda1q8BX2Xc2UQ";
      // YU 把陈总监给的KEY 填入
      "pk.eyJ1IjoiYW9mZW5nMjAwMCIsImEiOiJja252a3Q4cWkwazU3MnZwZDZ2MDN0MDg5In0.7HHfJfVC4Mht7IeL5yO4kQ";
      var mapStyle = {
        version: 8,
        name: "Dark",
        sources: {
          mapbox: {
            type: "vector",
            url: "mapbox://mapbox.mapbox-streets-v8"
          },
          overlay: {
            type: "image",
            url: this.imageUrl,
            coordinates: this.coordinates
          }
        },
        layers: [
          {
            id: "overlay",
            source: "overlay",
            type: "raster"
          }
        ]
      };
      this.map = new mapboxgl.Map({
        style: mapStyle,
        center: [0, 0], //地图中⼼经纬度
        zoom: this.zoom, //缩放级别
        // minZoom: 15.5,
        maxZoom: 24,
        pitch: 0,
        // bearing: -17.6,
        container: this.$refs.map,
        zoomAdjust: null,
        antialias: true,
        dragRotate: false,
        touchZoomRotate: false
      });
      // if(this.geojson.features.length > 0) {
      // this.geojson.features.forEach(item => {
      //调用创建dom 生成marker 方法
      // this.initMarker(item);
      // });
      // }
    },
    // 创建dom 元素生成 marker

    initMarker(data) {
      // 创建一个点
      var el = document.createElement("div");
      el.className = "marker";
      el.style.backgroundSize = "36px";
      el.style.backgroundRepeat = "no-repeat";
      el.style.backgroundPosition = "center";
      el.style.backgroundImage = "url(point.png)";
      el.style.cursor = "grab";
      el.addEventListener("click", e => {
        // console.log(data);
        e.stopPropagation();
        // console.log("点击的玩意", data.properties);
        // window.alert(data.properties.message);
      });
      // 创建文字信息
      var textEl = document.createElement("div");
      textEl.className = "marker";
      textEl.textContent = data.properties.message;
      textEl.style.backgroundColor = "rgba(51,51,51,.7)";
      textEl.style.height = "20px";
      textEl.style.borderRadius = "3px";
      textEl.style.paddingLeft = "5px";
      textEl.style.paddingRight = "5px";
      textEl.style.marginTop = "50px";
      textEl.style.display = "inline-block";
      textEl.style.color = "#3ED385";
      el.appendChild(textEl);
      textEl.addEventListener("click", e => {
        // console.log(data);
        e.stopPropagation();
        // window.alert(data.properties.message);
      });

      // 创建删除
      var del = document.createElement("span");
      del.className = "del";
      del.textContent = `×`;
      del.style.marginLeft = "5px";
      del.style.color = "#000";
      del.style.fontSize = "15px";
      del.style.display = "inline-block";
      del.style.backgroundColor = "red";
      del.style.width = "14px";
      del.style.height = "14px";
      del.style.borderRadius = "50%";
      del.style.textAlign = "center";
      del.style.lineHeight = "13px";
      del.style.cursor = "pointer";
      textEl.appendChild(del);
      // add marker to map
      var marker = new mapboxgl.Marker(el)
        .setLngLat(data.geometry.coordinates)
        .setDraggable(true)
        .addTo(this.map);
      this.arr.push(marker);
      del.addEventListener("click", e => {
        // console.log("删除的玩意", marker);
        // alert("删除的玩意"+ marker.data.message)
        e.stopPropagation();
        marker.remove();
        this.pointList.map((v, index) => {
          if (v.properties.id === marker.data.id) {
            this.pointList.splice(index, 1);
          }
        });
        this.list.map(v => {
          if (v.name === marker.data.message) {
            v.disabled = false;
          }
        });
      });

      marker.data = data.properties;
      marker.on("dragend", e => {
        // console.log("移动的玩意", marker);
        // alert("移动的玩意"+ marker.data.message)
        //鼠标移动开始
        // console.log("鼠标移动结束", marker.getLngLat(), marker.data);
        this.pointList.map((v, index) => {
          if (v.properties.id === marker.data.id) {
            v.geometry.coordinates = [
              marker.getLngLat().lng,
              marker.getLngLat().lat
            ];
          }
        });
      });
    },
    // 点击地图的方法
    clickMap() {
      this.map.on("click", e => {
        if (this.imageUrl !== "") {
          // if(this.imageUrl !== '' && this.isShow) {
          // 点击前可以初始化弹出框
          this.add = true;
          this.e = e;
        } else {
          this.add = false;
        }
      });
    },
    //提交
    save() {
      // console.log("didiidididiidididi",this.pointList)
      let params = {
        id: this.value.id,
        sectionName: this.value.sectionName,
        status: this.value.status,
        code: this.value.code,
        picturePath: this.path,
        remark: this.value.remark,
        ownId: this.ownId,
        lat: this.value.lat,
        lng: this.value.lng,
        sectionId: this.sectionId,
        viewList: this.pointList,
        coordinates: this.coordinates
      }
      let arr = []
      if(this.pointList.length > 0) {
          this.pointList.map(v => {
              let obj = {}
              obj.id = v.properties.id
              obj.code = v.properties.code
              obj.lng = v.geometry.coordinates[0]
              obj.lat = v.geometry.coordinates[1]
              arr.push(obj)
          })
          this.repeatList = arr
          let temp = []
          this.repeatList.map(v => {
            this.list.map(v1 =>{
              if(v.id === v1.id){
                let obj = {}
                obj.id = v.id
                obj.code = v.code
                obj.lng = v.lng
                obj.lat = v.lat
                obj.xaxis = v1.xaxis ? v1.xaxis : '0'
                obj.yaxis = v1.yaxis ? v1.yaxis : '0'
                temp.push(obj)
              }
            })
          })
          this.repeatList = temp
          // console.log(this.repeatList,'1234')
      }
      // console.log(this.pointList)
      if (this.path === "") {
        this.$vs.notify({
          text: "请上传图片",
          color: "danger"
        });
      } else {
        this.$api.bridge.updateBridgeCrossSection(params).then(res => {
          if (res.data.success) {
            let data = res.data.data;
            this.path = data.picturePath;
            this.imageUrl = this.download + data.picturePath;
            let obj = {
              name: "111.png",
              url: this.imageUrl
            };
            this.imgList = [obj];

            this.$vs.notify({
              text: "测点配置成功",
              color: "success"
            });
            this.get();
          } else {
            this.$vs.notify({
              text: "测点配置失败",
              color: "danger"
            });
          }
        });
        this.$api.bridge.batchUpdateDeviceMeasurePoint(this.repeatList).then(res => {
            if(res.data.success) {

            }
        })
      }
    },
    //查询
    get() {
        let data = this.value;
          this.first = true;
        if (data.picturePath !== '') {
            this.path = data.picturePath;
            this.imageUrl = this.download + data.picturePath;
            let obj = {
              name: "111.png",
              url: this.imageUrl
            };
            this.imgList = [obj];
            this.noshowUpload = true;
            if(data.coordinates) {
                this.coordinates = data.coordinates
            } else {
                 var img = new Image();
                img.src = this.download + this.path;
                img.onload = () => {
                    this.proportion = (Number(img.width) / Number(img.height)).toFixed(2);
                    let xPoint = this.proportion * this.yPoint;
                    this.coordinates = [
                    [-xPoint, this.yPoint],
                    [xPoint, this.yPoint],
                    [xPoint, -this.yPoint],
                    [-xPoint, -this.yPoint]
                    ];
                };
            }
          } else {
            this.path = data.picturePath;
            this.imageUrl = require("../../../assets/mapbox/bg.png");
            this.imgList = [];
            this.noshowUpload = false;
            this.coordinates = [
        [-76.54335737228394, 39.18579907229748],
        [-76.52803659439087, 39.1838364847587],
        [-76.5295386314392, 39.17683392507606],
        [-76.54520273208618, 39.17876344106642]
      ]
          }
          this.pointList = data.viewList || [];
          var map = this.map.getSource("overlay");
          map.updateImage({ url: this.imageUrl });
          map.setCoordinates(this.coordinates);
          this.arr.map(v => {
            v.remove();
          })
          if (this.pointList.length > 0) {
            this.pointList.forEach(item => {
              //调用创建dom 生成marker 方法
              this.initMarker(item);
            });
          }
          if (data.viewList && data.viewList.length > 0) {
            if (this.list.length > 0) {
              data.viewList.map(v => {
                this.list.map(v1 => {
                  if (v.properties.id === v1.id) {
                    v1.disabled = true;
                  }
                });
              });
            }
          }
    },
    getMap() {
      this.initMap();
      this.clickMap();
    }
  }
};
</script>

<style scoped lang="scss">
.top {
  /* border-bottom:1px solid #eee; */
  display: flex;
  align-items: center;
  height: 100px;
  position: fixed;
  z-index: 100 !important;
}
.up {
  margin-right: 10px;
}
/deep/.uoloadSty .el-upload--picture-card {
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 28px;
}
/deep/.disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
/deep/.el-upload-list--picture-card .el-upload-list__item {
  width: 60px;
  height: 60px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.mapContain {
  width: 100%;
}

.map {
  width: 100%;
  margin: 20px 0;
  height: 400px;
}
.tabContent {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding-bottom: 30px;
  border-bottom: 1px solid #e3e8f2;
}
.tab {
  width: 70px;
  height: 34px;
  background: $mainColor;
  border-radius: 17px;
  text-align: center;
  line-height: 34px;
  color: #fff;
  font-size: 14px;
}
</style>
